import { login, signup } from "wasp/client/auth";
import React, { useState } from "react";
import ProForm, { ProFormText } from "@ant-design/pro-form";
import { PageContainer } from "@ant-design/pro-layout";
import { Card, Button, message } from "antd";
import { useNavigate } from "react-router-dom";

export const LoginPage: React.FC = () => {
  const [loading, setLoading] = useState(false);

  const [form] = ProForm.useForm();
  const navigate = useNavigate();

  const onFinish = async (values: any) => {
    setLoading(true);

    try {
      // 登录
      await login(values.username, values.password);
      // 跳转到主页面
      navigate("/");
    } catch (error: unknown) {
      message.error("登录失败，请检查用户名和密码");
      // TODO 添加日志功能
    }

    setLoading(false);
  };

  return (
    <div>
      <Card title="用户登录" style={{ maxWidth: 400, margin: "0 auto" }}>
        <ProForm
          form={form}
          onFinish={onFinish}
          submitter={{
            render: (_, dom) => (
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <Button htmlType="button" onClick={() => form.resetFields()}>
                  重置
                </Button>
                <Button loading={loading} type="primary" htmlType="submit">
                  登录
                </Button>
              </div>
            ),
          }}
        >
          <ProFormText
            name="username"
            label="用户名"
            rules={[{ required: true }]}
          />
          <ProFormText.Password
            name="password"
            label="密码"
            rules={[{ required: true }]}
          />
        </ProForm>
      </Card>
    </div>
  );
};
